import { Button, Form, Input } from 'antd';
import type { FormProps } from 'antd';
import { useNavigate } from 'react-router-dom'
import { LoginApi } from '@/api/user'
import { setToken } from '@/redux/slices/user'
import { useDispatch } from 'react-redux';
// import { useAuth } from '@/context/AuthContext';
import './index.scss'
import { useAuth } from '@/context/AuthContext';


const Login: React.FC = () => {

  const { login } = useAuth()

  const navigate = useNavigate()

  const dispatch = useDispatch()

  const onFinish: FormProps<LoginApiRequest>['onFinish'] = (values) => {
    console.log(values)
    LoginApi(values).then(async res => {
      if (res.status === 0) {
        dispatch(setToken(res.data?.token))
        login(res.data?.token!)
        navigate('/home')
      }
    })
  };

  const onFinishFailed: FormProps<LoginApiRequest>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return <div className="login">
    <Form
      name="loginForm"
      labelCol={{ span: 5, }}
      wrapperCol={{ span: 19 }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item<LoginApiRequest>
        label="用户名"
        name="username"
        rules={[{ required: true, message: '请输入用户名' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item<LoginApiRequest>
        label="密码"
        name="password"
        rules={[{ required: true, message: '请输入密码' }]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item label={null}>
        <Button type="primary" htmlType="submit">
          登录
        </Button>
      </Form.Item>
    </Form>
  </div>
}

export default Login;